package com.nc.user.config.shiro;


import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import com.nc.user.dao.FrmPermissionsDao;
import com.nc.user.dao.FrmRoleDao;
import com.nc.user.dao.FrmUsersDao;
import com.nc.user.model.entity.FrmPermissions;
import com.nc.user.model.entity.FrmRole;
import com.nc.user.model.entity.FrmUsers;
import com.nc.user.tool.tool.EDcrypionUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;


import java.io.UnsupportedEncodingException;
import java.util.Collection;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;

public class UserRealm extends AuthorizingRealm {
    private Logger logger = LoggerFactory.getLogger(AuthorizingRealm.class);

    @Autowired
    private FrmUsersDao usersDao;

    @Autowired
    private FrmRoleDao frmRoleDao;

    @Autowired
    private FrmPermissionsDao frmPermissionsDao;

    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        FrmUsers fspUser = (FrmUsers) principalCollection.getPrimaryPrincipal();
        Collection<String> roles = new LinkedHashSet<>();
        Set<String> permissions = new LinkedHashSet<>();
        List<String> roleCode = Lists.newArrayList();
        fspUser.getFrmRoles().stream().forEach(item->{
            roleCode.add(item.getCode());
            roles.add(item.getCode());
        });
        frmPermissionsDao.findByFrmRolesCode(roleCode).stream().forEach(item->{
            permissions.add(item.getCode());
        });
        authorizationInfo.addRoles(roles);
        authorizationInfo.addStringPermissions(permissions);
        return authorizationInfo;
    }

    //登录
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        //1，获得前端传值

        String username = (String) authenticationToken.getPrincipal();
        FrmUsers user = usersDao.findByMobile(username);
        if (user == null || user.getStatus() == false) {
            user = null;
        }
        if (user == null) {
            //没找到帐号
            throw new UnknownAccountException();
        }
        List<FrmRole> lx = frmRoleDao.findByUserId(user.getId());
        lx.stream().forEach(ls -> {
            ls.setPermissionsRole(null);
            ls.setFrmUsers(null);
        });
        user.setFrmRoles(lx);
        HashedCredentialsMatcher matcher = new HashedCredentialsMatcher();
        matcher.setHashIterations(10);
        matcher.setHashAlgorithmName("md5");

        this.setCredentialsMatcher(matcher);

        SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(user, user.getPassword(), "");
        //盐
        authenticationInfo.setCredentialsSalt(ByteSource.Util.bytes(EDcrypionUtils.key));
        //将用户信息放入session中
        SecurityUtils.getSubject().getSession().setTimeout(-1000l);
        user.setPassword("");
        SecurityUtils.getSubject().getSession().setAttribute("Users", user);
        return authenticationInfo;
    }

    //加密
    public static void main(String[] args) throws UnsupportedEncodingException {
        System.out.println(EDcrypionUtils.shiroPassword("123456"));
    }

}
